package org.gdpu.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import org.apache.struts2.ServletActionContext;
import org.gdpu.Service.ApplicationService;
import org.gdpu.Service.NewsService;
import org.gdpu.Service.StudentService;
import org.gdpu.Service.UserService;
import org.gdpu.model.*;
import org.gdpu.util.ChangeTime;
import org.gdpu.vo.ApplicationVO;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 14-3-6
 * Time: 下午2:45
 * To change this template use File | Settings | File Templates.
 */
@Component("application")
@Scope("prototype")
public class ApplicationAction extends MyActionSupport implements ModelDriven<ApplicationVO> {

    private final ApplicationVO applicationVO = new ApplicationVO();
    private ApplicationService applicationService;
    private StudentService studentService;
    private NewsService newsService;
    private UserService userService;
    private Application application;
    private final static Logger logger = LogManager.getLogger(ApplicationAction.class);

    //获取当前登录用户
    HttpSession session = ServletActionContext.getRequest().getSession();
    User person = (User) session.getAttribute("person");

    @Override
    public String execute() throws Exception {
        if (applicationVO.getApplyStu().isEmpty()) {
            applicationVO.setResultMessage("<script>alert('请选择申请的学生！');location.href='/page/dormitoryManagement/interChangeDormitory.jsp';</script>");
            return ERROR;
        }
        if (applicationVO.getDormitory().isEmpty() || applicationVO.getExchangeStu().isEmpty()) {
            applicationVO.setResultMessage("<script>alert('请选择呼唤宿舍的学生姓名！');location.href='/page/dormitoryManagement/interChangeDormitory.jsp';</script>");
            return ERROR;
        }
        application = new Application();
        Random random = new Random();
        application.setId(ChangeTime.formatDate(new Date()) + random.nextInt(9) % 10);
        application.setApplyState(ApplyState.WAIT);
        application.setApplyStudent(studentService.findStudent("studentId", Integer.valueOf(applicationVO.getApplyStu())).get(0));
        application.setExchange(studentService.findStudent("studentId", Integer.valueOf(applicationVO.getExchangeStu())).get(0));
        application.setApplyTime(new Date());
        application.setReMarks(applicationVO.getReMarks());
        applicationService.save(application);
        News news = newsService.createNews(application.getApplyStudent(), application.getExchange(), "换宿舍请求", "Application!showApplication.action?" + application.getId());
        if (news != null)
            newsService.save(news);
        else {
            applicationService.delete(application);
            applicationVO.setResultMessage("<script>alert('申请失败！');location.href='/page/dormitoryManagement/interChangeDormitory.jsp';</script>");
            return ERROR;
        }
        applicationVO.setResultMessage("<script>alert('申请成功！');location.href='/page/dormitoryManagement/interChangeDormitory.jsp';</script>");
        return SUCCESS;
    }

    public String showApplication() {
        application = applicationService.find(Application.class, applicationVO.getId());
        News news = newsService.find(News.class, Integer.valueOf(applicationVO.getNewsId()));
        applicationVO.setApplication(application);
        storeTargetToSession(news);
        view = "/page/dormitoryManagement/showApplication.jsp";
        return VIEW;
    }

    public String changeState() {
        application = applicationService.find(Application.class, applicationVO.getId());
        News news = newsService.find(News.class, Integer.valueOf(applicationVO.getNewsId()));
        if ("学生宿舍".equals(person.getPowerGroup().getPowerGroup())) {
            if (applicationVO.getReMarks().trim().isEmpty()) {
                application.setApplyState(ApplyState.DISAGREE);
            } else {
                application.setApplyState(ApplyState.APPLY);
                News otherNews = newsService.createNews(application.getApplyStudent(), userService.findByName("宿舍管理部"), "换宿舍请求", "Application!showApplication.action?" + application.getId());
                newsService.save(otherNews);
            }
        } else {
            if (applicationVO.getReMarks().trim().isEmpty()) {
                application.setApplyState(ApplyState.NOT_ALLOW);
            } else {
                application.setApplyState(ApplyState.ALLOW);
                application.setCheck(person);
                studentService.changeDormitory(application.getApplyStudent(), application.getExchange());
            }
        }
        applicationService.update(application);
        news.setNewsState(MailboxState.DEAL);
        newsService.update(news);
        applicationVO.setResultMessage("<script>alert('操作成功！');location.href='/index.jsp';</script>");
        return SUCCESS;
    }

    private void storeTargetToSession(News target) {
        HttpSession session = ServletActionContext.getRequest().getSession();
        News storeTarget = (News) session.getAttribute("news");
        if (storeTarget == null || !storeTarget.equals(target)) {
            session.setAttribute("news", target);
            session.setMaxInactiveInterval(-1);
        }
    }

    @Resource(name = "applicationServiceImpl")
    public void setApplicationService(ApplicationService applicationService) {
        this.applicationService = applicationService;
    }

    @Resource(name = "studentServiceImpl")
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }

    @Resource(name = "newsServiceImpl")
    public void setNewsService(NewsService newsService) {
        this.newsService = newsService;
    }

    @Resource(name = "userServiceImpl")
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public ApplicationVO getModel() {
        return applicationVO;
    }
}
